package com.lml.gpt;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @author luomingliang
 * @date 2023/3/6 20:00
 */
public class SHA256Example {

    public static void main(String[] args) {
        String input = "Hello World!";
        String sha256Hash = getSHA256Hash(input);
        System.out.println("SHA-256 Hash of \"" + input + "\" is: " + sha256Hash);
    }

    public static String getSHA256Hash(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] encodedHash = digest.digest(input.getBytes(StandardCharsets.UTF_8));

            StringBuilder hexString = new StringBuilder();
            for (byte b : encodedHash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
